import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  TextInput,
  Modal,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Simple text-based icons
const Icon = ({ name, size = 24, color = '#000' }: { name: string; size?: number; color?: string }) => {
  const iconMap: { [key: string]: string } = {
    'arrow-back': '⬅️',
    'arrow-down': '▼',
    'calendar': '📅',
  };

  return (
    <Text style={{ fontSize: size, color, textAlign: 'center' }}>
      {iconMap[name] || '📱'}
    </Text>
  );
};

interface DropdownOption {
  label: string;
  value: string;
}

const QingjiaApplication: React.FC = () => {
  const navigation = useNavigation();
  const [formData, setFormData] = useState({
    applicant: '',
    leaveType: '请选择',
    startTime: '',
    endTime: '',
    leaveDuration: '1天',
    reason: '',
  });

  // Dropdown states
  const [showLeaveTypeDropdown, setShowLeaveTypeDropdown] = useState(false);
  const [showStartTimePicker, setShowStartTimePicker] = useState(false);
  const [showEndTimePicker, setShowEndTimePicker] = useState(false);

  // Time picker state
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [selectedHour, setSelectedHour] = useState(9);
  const [selectedMinute, setSelectedMinute] = useState(0);

  // Dropdown options
  const leaveTypeOptions: DropdownOption[] = [
    { label: '年假', value: '年假' },
    { label: '事假', value: '事假' },
    { label: '病假', value: '病假' },
    { label: '调休', value: '调休' },
    { label: '婚假', value: '婚假' },
    { label: '其他', value: '其他' },
  ];

  const hours = Array.from({ length: 24 }, (_, i) => i);
  const minutes = Array.from({ length: 60 }, (_, i) => i);

  const handleOptionSelect = (field: string, value: string) => {
    setFormData({ ...formData, [field]: value });
    setShowLeaveTypeDropdown(false);
  };

  const handleTimeSelect = (isStartTime: boolean) => {
    const formattedDate = selectedDate.toISOString().split('T')[0];
    const formattedHour = selectedHour.toString().padStart(2, '0');
    const formattedMinute = selectedMinute.toString().padStart(2, '0');
    const timeString = `${formattedDate} ${formattedHour}:${formattedMinute}`;
    
    if (isStartTime) {
      setFormData(prev => ({ ...prev, startTime: timeString }));
      setShowStartTimePicker(false);
    } else {
      setFormData(prev => ({ ...prev, endTime: timeString }));
      setShowEndTimePicker(false);
    }
    
    // 计算请假时长
    setTimeout(() => {
      if (isStartTime) {
        // 如果设置了开始时间，检查是否已有结束时间
        if (formData.endTime) {
          calculateDuration();
        }
      } else {
        // 如果设置了结束时间，检查是否已有开始时间
        if (formData.startTime) {
          calculateDuration();
        }
      }
    }, 100);
  };

  const calculateDuration = () => {
    if (formData.startTime && formData.endTime) {
      const start = new Date(formData.startTime);
      const end = new Date(formData.endTime);
      const diffMs = end.getTime() - start.getTime();
      const diffHours = Math.ceil(diffMs / (1000 * 60 * 60));
      
      if (diffHours <= 24) {
        setFormData(prev => ({ ...prev, leaveDuration: `${diffHours}小时` }));
      } else {
        const diffDays = Math.ceil(diffHours / 24);
        setFormData(prev => ({ ...prev, leaveDuration: `${diffDays}天` }));
      }
    }
  };

  const validateForm = (): boolean => {
    if (!formData.applicant.trim()) {
      Alert.alert('提示', '请填写申请人姓名');
      return false;
    }
    if (formData.leaveType === '请选择') {
      Alert.alert('提示', '请选择请假类型');
      return false;
    }
    if (!formData.startTime) {
      Alert.alert('提示', '请选择开始时间');
      return false;
    }
    if (!formData.endTime) {
      Alert.alert('提示', '请选择结束时间');
      return false;
    }
    if (!formData.reason.trim()) {
      Alert.alert('提示', '请填写请假事由');
      return false;
    }
    return true;
  };

  const saveToLocalStorage = async (data: any) => {
    try {
      const existingData = await AsyncStorage.getItem('applications');
      const applications = existingData ? JSON.parse(existingData) : [];
      
      const newApplication = {
        id: Date.now().toString(),
        type: '请假申请',
        title: '请假申请',
        applicant: formData.applicant,
        details: `${formData.leaveType} - ${formData.leaveDuration}`,
        applicationTime: new Date().toLocaleString('zh-CN'),
        status: '待审批',
        data: data,
        category: '人事管理',
      };
      
      applications.unshift(newApplication);
      await AsyncStorage.setItem('applications', JSON.stringify(applications));
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      await saveToLocalStorage(formData);
      Alert.alert('提示', '提交完成', [
        {
          text: '确定',
          onPress: () => (navigation as any).navigate('AllApplications'),
        },
      ]);
    } catch (error) {
      Alert.alert('错误', '提交失败，请重试');
    }
  };

  const renderDropdown = (
    visible: boolean,
    options: DropdownOption[],
    onSelect: (value: string) => void,
    onClose: () => void
  ) => (
    <Modal
      visible={visible}
      transparent={true}
      animationType="fade"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.dropdownContainer}>
          {options.map((option, index) => (
            <TouchableOpacity
              key={index}
              style={styles.dropdownOption}
              onPress={() => onSelect(option.value)}
            >
              <Text style={styles.dropdownOptionText}>{option.label}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </TouchableOpacity>
    </Modal>
  );

  const renderTimePicker = (visible: boolean, onClose: () => void, onConfirm: () => void) => (
    <Modal
      visible={visible}
      transparent={true}
      animationType="slide"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.timePickerContainer}>
          <View style={styles.timePickerHeader}>
            <Text style={styles.timePickerTitle}>选择时间</Text>
            <TouchableOpacity onPress={onConfirm}>
              <Text style={styles.confirmButton}>确定</Text>
            </TouchableOpacity>
          </View>
          
          <View style={styles.timePickerContent}>
            <View style={styles.timePickerColumn}>
              {hours.map(hour => (
                <TouchableOpacity
                  key={hour}
                  style={[
                    styles.timePickerItem,
                    selectedHour === hour && styles.selectedTimeItem
                  ]}
                  onPress={() => setSelectedHour(hour)}
                >
                  <Text style={[
                    styles.timePickerItemText,
                    selectedHour === hour && styles.selectedTimeItemText
                  ]}>
                    {hour.toString().padStart(2, '0')}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
            <Text style={styles.timePickerSeparator}>:</Text>
            <View style={styles.timePickerColumn}>
              {minutes.map(minute => (
                <TouchableOpacity
                  key={minute}
                  style={[
                    styles.timePickerItem,
                    selectedMinute === minute && styles.selectedTimeItem
                  ]}
                  onPress={() => setSelectedMinute(minute)}
                >
                  <Text style={[
                    styles.timePickerItemText,
                    selectedMinute === minute && styles.selectedTimeItemText
                  ]}>
                    {minute.toString().padStart(2, '0')}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
        </View>
      </TouchableOpacity>
    </Modal>
  );

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={20} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>请假申请</Text>
        <View style={styles.headerSpacer} />
      </View>

      {/* Content */}
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* Basic Information Section */}
        <View style={styles.section}>
          <View style={styles.infoRow}>
            <Text style={styles.label}>申请人</Text>
            <TextInput
              style={styles.textInput}
              placeholder="请输入申请人姓名"
              placeholderTextColor="#999"
              value={formData.applicant}
              onChangeText={(text) => setFormData({...formData, applicant: text})}
            />
          </View>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowLeaveTypeDropdown(true)}
          >
            <Text style={styles.label}>请假类型</Text>
            <View style={styles.infoValue}>
              <Text style={[
                styles.valueText,
                formData.leaveType === '请选择' && styles.placeholderText
              ]}>
                {formData.leaveType}
              </Text>
              <Icon name="arrow-down" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowStartTimePicker(true)}
          >
            <Text style={styles.label}>开始时间</Text>
            <View style={styles.infoValue}>
              <Text style={[
                styles.valueText,
                !formData.startTime && styles.placeholderText
              ]}>
                {formData.startTime || '请选择'}
              </Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowEndTimePicker(true)}
          >
            <Text style={styles.label}>结束时间</Text>
            <View style={styles.infoValue}>
              <Text style={[
                styles.valueText,
                !formData.endTime && styles.placeholderText
              ]}>
                {formData.endTime || '请选择'}
              </Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <View style={styles.infoRow}>
            <Text style={styles.label}>请假时长</Text>
            <Text style={styles.valueText}>{formData.leaveDuration}</Text>
          </View>
        </View>

        {/* Reason Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>请假事由</Text>
          <TextInput
            style={styles.textArea}
            placeholder="请输入"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            value={formData.reason}
            onChangeText={(text) => setFormData({...formData, reason: text})}
          />
        </View>

        {/* Approval Process Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>审批流程</Text>
          <View style={styles.approvalFlow}>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>1</Text>
              </View>
              <Text style={styles.flowLabel}>发起人</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>2</Text>
              </View>
              <Text style={styles.flowLabel}>部门领导</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>3</Text>
              </View>
              <Text style={styles.flowLabel}>人事部</Text>
            </View>
          </View>
        </View>

        {/* Submit Button */}
        <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
          <Text style={styles.submitButtonText}>提交</Text>
        </TouchableOpacity>
      </ScrollView>

      {/* Dropdowns */}
      {renderDropdown(
        showLeaveTypeDropdown,
        leaveTypeOptions,
        (value) => handleOptionSelect('leaveType', value),
        () => setShowLeaveTypeDropdown(false)
      )}
      {renderTimePicker(
        showStartTimePicker,
        () => setShowStartTimePicker(false),
        () => handleTimeSelect(true)
      )}
      {renderTimePicker(
        showEndTimePicker,
        () => setShowEndTimePicker(false),
        () => handleTimeSelect(false)
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerSpacer: {
    width: 28,
  },
  content: {
    flex: 1,
    paddingHorizontal: 16,
  },
  section: {
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  label: {
    fontSize: 16,
    color: '#333',
    width: 80,
  },
  textInput: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    textAlign: 'right',
  },
  infoValue: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  valueText: {
    fontSize: 16,
    color: '#333',
    marginRight: 8,
  },
  placeholderText: {
    color: '#999',
  },
  separator: {
    height: 1,
    backgroundColor: '#e0e0e0',
  },
  textArea: {
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: '#333',
    minHeight: 100,
    textAlignVertical: 'top',
  },
  approvalFlow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  flowStep: {
    alignItems: 'center',
    flex: 1,
  },
  flowNode: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#6c5ce7',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 8,
  },
  flowNodeText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  flowLabel: {
    fontSize: 12,
    color: '#333',
    textAlign: 'center',
  },
  flowArrow: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 20,
  },
  arrowText: {
    fontSize: 18,
    color: '#999',
  },
  submitButton: {
    backgroundColor: '#6c5ce7',
    borderRadius: 8,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 32,
    marginBottom: 32,
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  dropdownContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 8,
    minWidth: 200,
    maxHeight: 300,
    alignSelf: 'center',
    marginBottom: 100,
  },
  dropdownOption: {
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  dropdownOptionText: {
    fontSize: 16,
    color: '#333',
  },
  timePickerContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    padding: 20,
  },
  timePickerHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  timePickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#6c5ce7',
    fontWeight: '600',
  },
  timePickerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 200,
  },
  timePickerColumn: {
    width: 80,
    height: 200,
  },
  timePickerItem: {
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selectedTimeItem: {
    backgroundColor: '#6c5ce7',
    borderRadius: 20,
  },
  timePickerItemText: {
    fontSize: 16,
    color: '#333',
  },
  selectedTimeItemText: {
    color: '#fff',
    fontWeight: '600',
  },
  timePickerSeparator: {
    fontSize: 24,
    color: '#333',
    marginHorizontal: 20,
  },
});

export default QingjiaApplication;
